<?php

/**
 * 获取图片
 * @param  [type] $img [description]
 * @return [type]      [description]
 */
function getimg($imgs, $num = 1)
{
    return getfile($imgs, $num);
}

/**
 * 获取文件
 * @param  [type] $file [description]
 * @return [type]      [description]
 */
function getfile($imgs, $num = 1)
{
    if (is_array($imgs)) {
        $key = 1;
        foreach ($imgs as $img) {
            if ($key == $num) {
                return $img['file_path'];
            }
            $key++;
        }
    }
    return '';
}

/**
 * [dp_prefix 无限分类 下拉菜单 前缀]
 * @param  [type] $path [description]
 * @return [type]       [description]
 */
function dp_prefix($path)
{
    return str_repeat('•••', substr_count($path, ','));
}

/**
 * 复制数组文件
 * @param  [type] $files [数组]
 * @return [type]        [数组]
 */
function copy_files($files)
{
    $new_files = array();
    if (!is_array($files)) {
        return $new_files;
    }
    foreach ($files as $key => $file) {
        $file_path = $file['file_path'];
        $news_path = copy_file($file_path);
        if (!$news_path) {
            continue;
        }
        //
        $new_files[] = [
            'file_path' => $news_path,
            'file_name' => $file['file_name'],
            'file_size' => $file['file_size'],
            'file_ext' => $file['file_ext'],
        ];
    }
    return $new_files;
}

/**
 * 复制单个文件
 * @param  [type] $file [文件路径]
 * @return [type]       [路径]
 */
function copy_file($file)
{
    if (!file_exists('.' . $file)) {
        return false;
    }
    $file_ext = strrchr($file, '.');
    $news_path = dirname($file);
    $news_path .= '/' . uniqid() . $file_ext;
    // 复制文件
    if (!copy('.' . $file, '.' . $news_path)) {
        return false;
    }
    return $news_path;
}

/**
 * 判断数组中是否有target字段
 * @param  [type]  $item [字段列表]
 * @return boolean       [返回链接跳出方式]
 */
function is_target($item)
{
    if (isset($item['target'])) {
        return $item['target'];
    }

    return false;
}

/**
 * 判断栏目是否被选中。
 * @param  [type]  $active [当前字段]
 * @param  [type]  $barname [导航ID]
 * @return boolean         [选中返回active]
 */
function is_active($active = '', $barname = '')
{
    if ($active == '' || $barname == '') {
        return false;
    }

    if ($active == $barname) {
        return 'active';
    }

    return false;
}

/**
 * [get_upload_max 上传限制]
 * @return [type] [description]
 */
function get_upload_max()
{
    if (@ini_get('file_uploads')) {
        return ini_get('upload_max_filesize');
    }

    return '0';
}

/**
 * [get_db_version 获取数据库版本]
 * @return [type] [description]
 */
function get_db_version()
{
    if (config('database.type') == 'mysql') {
        $db = Db::query("select version()");
        if (isset($db[0]['version()'])) {
            return $db[0]['version()'];
        }
    }

    return '0.0.0';
}

/**
 * [make_param 生成表单控件]
 * @return [type] [description]
 */
function make_controls($item = [])
{
    $param = [
        'param_id' => 0,
        'param_name' => '',
        'param_type' => 'text',
        'param_required' => '0',
        'param_value' => '',
    ];
    $param = array_merge($param, $item);

    $id = 'param_' . $param['param_id'];
    $name = $id;
    $placeholder = $param['param_name'];
    $type = $param['param_type'];
    $value = $param['param_value'];
    $required = $param['param_required'] == 1 ? 'required' : '';

    $code = '';
    switch ($param['param_type']) {
        case 'text':
        case 'number':
        case 'email':
            $code = sprintf('<input class="form-control" type="%s" id="%s" name="%s" placeholder="%s" value="%s" %s>', $type, $id, $name, $placeholder, $value, $required);
            break;
        case 'textarea':
            $code = sprintf('<textarea class="form-control" id="%s" name="%s" placeholder="%s" %s>%s</textarea>', $id, $name, $placeholder, $required, $value);
            break;
        case 'select':
            $code = sprintf('<select class="form-control" id="%s" name="%s" placeholder="%s" %s>', $id, $name, $placeholder, $required);
            $arg = explode("\n", $value);
            foreach ($arg as $key => $value) {
                $code .= trim($value) == '' ?: sprintf('<option value="%s">%s</option>', $value, $value);
            }
            $code .= '</select>';
            break;
        case 'checkbox':
            $arg = explode("\n", $value);
            foreach ($arg as $key => $value) {
                $code .= trim($value) == '' ?: sprintf('<label class="checkbox-inline"><input type="checkbox" name="%s[]" value="%s">%s &nbsp; &nbsp;</label>', $name, $value, $value);
            }
            break;
        case 'radio':
            $arg = explode("\n", $value);
            foreach ($arg as $key => $value) {
                $code .= trim($value) == '' ?: sprintf('<label class="radio-inline"><input type="radio" name="%s" value="%s" %s>%s &nbsp; &nbsp;</label>', $name, $value, $required, $value);
            }
            break;
        case 'image':
            $code .= '<div class="input-group">';
            $code .= sprintf('<input type="text" class="form-control" name="%s" placeholder="选择文件: jpg, png, gif" readonly>', $name);
            $code .= '<span class="input-group-btn">';
            $code .= sprintf('<button type="button" class="btn text-primary" data-param-upload data-param-type="image" data-input-name="%s">上传</button>', $name);
            $code .= sprintf('<button type="button" class="btn text-success" data-param-preview data-input-name="%s">预览</button>', $name);
            $code .= sprintf('<button type="button" class="btn text-danger" data-param-delete data-input-name="%s">删除</button>', $name);
            $code .= '</span>';
            $code .= '</div>';
            break;
        case 'file':
            $code .= '<div class="input-group">';
            $code .= sprintf('<input type="text" class="form-control" name="%s" placeholder="选择文件: txt, pdf, zip, gzip" readonly>', $name);
            $code .= '<span class="input-group-btn">';
            $code .= sprintf('<button type="button" class="btn text-primary" data-param-upload data-param-type="file" data-input-name="%s">上传</button>', $name);
            $code .= sprintf('<button type="button" class="btn text-success" data-param-download data-input-name="%s">下载</button>', $name);
            $code .= sprintf('<button type="button" class="btn text-danger" data-param-delete data-input-name="%s">删除</button>', $name);
            $code .= '</span>';
            $code .= '</div>';
            break;
        case 'editor':
            $code = sprintf('<script id="%s" name="%s" class="ueditor" type="text/plain">%s</script>', $id, $name, $value);
            //$code = sprintf('<textarea class="form-control tinymce" id="%s" name="%s">%s</textarea>', $id, $name, $value);
            break;
        default:
            $code = sprintf('未定义 <code>%s</code> 类型的表单控件', $type);
            break;
    }
    return $code;
}

/**
 * [admin_config_app 保存配置文件]
 * @return [type] [description]
 */
function admin_config_app($data)
{
    if (!is_array($data) || empty($data)) {
        return false;
    }

    // 获取项目配置文件路径
    $path = env('app_path');
    $path .= 'admin/config/app.php';

    if (!file_exists($path)) {
        return false;
    }

    // 加载配置文件
    $config = include $path;
    $config = array_merge($config, $data);
    //dump($config);

    // 生成配置文件
    $code = '<?php ' . PHP_EOL;
    $code .= '/** admin 模块文件配置 **/' . PHP_EOL;
    $code .= 'return ' . var_export($config, true) . ';';
    return file_put_contents($path, $code);
}

/**
 * [admin_config_setting 保存配置文件]
 * @return [type] [description]
 */
function admin_config_setting($data)
{
    if (!is_array($data) || empty($data)) {
        return false;
    }

    // 获取项目配置文件路径
    $path = env('app_path');
    $path .= 'admin/config/setting.php';

    if (!file_exists($path)) {
        return false;
    }

    // 加载配置文件
    $config = include $path;
    $config = array_merge($config, $data);
    //dump($config);

    // 生成配置文件
    $code = '<?php ' . PHP_EOL;
    $code .= '/** setting 模块文件配置 **/' . PHP_EOL;
    $code .= 'return ' . var_export($config, true) . ';';
    return file_put_contents($path, $code);
}

/**
 * [index_config_template 保存配置文件]
 * @return [type] [description]
 */
function index_config_template($data)
{
    if (!is_array($data) || empty($data)) {
        return false;
    }

    // 获取项目配置文件路径
    $path = env('app_path');
    $path .= 'index/config/template.php';

    if (!file_exists($path)) {
        return false;
    }

    // 加载配置文件
    $config = include $path;
    $config = array_merge($config, $data);
    //dump($config);

    // 生成配置文件
    $code = '<?php ' . PHP_EOL;
    $code .= '/** template 模块文件配置 **/' . PHP_EOL;
    $code .= 'return ' . var_export($config, true) . ';';
    return file_put_contents($path, $code);
}

/**
 * [func_env 保存配置文件]
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function func_env($data)
{
    $default = [
        'app_debug' => 1,
        'type' => 'mysql',
        'hostname' => '127.0.0.1',
        'database' => 'site',
        'username' => 'root',
        'password' => 'root',
        'hostport' => 'site_',
        'prefix' => '3306',
    ];

    $default = array_merge($default, $data);

    $path = env('root_path');
    $path = $path . '.env';

    $code = '';
    $code .= '[app]' . PHP_EOL;
    $code .= 'app_debug = ' . $default['app_debug'] . PHP_EOL;
    $code .= '' . PHP_EOL;
    $code .= '[database]' . PHP_EOL;
    $code .= 'type = ' . $default['type'] . PHP_EOL;
    $code .= 'hostname = ' . $default['hostname'] . PHP_EOL;
    $code .= 'database = ' . $default['database'] . PHP_EOL;
    $code .= 'username = ' . $default['username'] . PHP_EOL;
    $code .= 'password = ' . $default['password'] . PHP_EOL;
    $code .= 'hostport = ' . $default['hostport'] . PHP_EOL;
    $code .= 'prefix = ' . $default['prefix'] . PHP_EOL;
    return file_put_contents($path, $code);
}

/**
 * 生成 index 路由
 * @param  [type] $site [description]
 * @return [type]       [description]
 */
function make_index_route($sites = [])
{
    $save_path = env('root_path') . 'route/';
    $temp_path = env('app_path') . 'index/temp/';
    $code = '<?php ' . PHP_EOL;
    foreach ($sites as $key => $site) {
        $site_name = $site['site_name'];
        $site_mark = $site['site_mark'];
        $file = $temp_path . ($site['site_default'] == 1 ? 'index.route' : 'site.route');
        if (!file_exists($file)) {
            continue;
        }

        $code .= '' . PHP_EOL;
        $code .= '// ' . $site_name . PHP_EOL;
        // 路由代码
        $code_route = '';
        $code_route = file_get_contents($file);
        $code_route = str_replace('{site_mark}', strtolower($site_mark), $code_route);
        $code_route = str_replace('{uc_site_mark}', ucfirst($site_mark), $code_route);
        $code .= $code_route . PHP_EOL;
    }
    $code .= '' . PHP_EOL;
    $code .= '// 控制器 index/controller/EmptyController.php' . PHP_EOL;
    $path = $save_path . 'index.php';
    return file_put_contents($path, $code);
}

/**
 * 生成 index 控制器
 * @return [type] [description]
 */
function make_index_controller($sites = [])
{
    $path = env('app_path') . 'index/';
    $save_path = $path . 'controller/';
    $temp_path = $path . 'temp/';
    foreach ($sites as $key => $site) {
        $site_mark = $site['site_mark'];
        $controller = ucfirst($site_mark) . 'Controller';

        $file = $temp_path . 'site.controller';
        if (!file_exists($file)) {
            continue;
        }
        // 生成EmptyController控制器
        $code = file_get_contents($file);
        $code = str_replace('{site_mark}', ucfirst($site_mark), $code);
        file_put_contents($save_path . ucfirst($site_mark) . 'Controller.php', $code);

        if ($site['site_default'] == 1) {
            $file = $temp_path . 'empty.controller';
            // 生成EmptyController控制器
            $code = file_get_contents($file);
            $code = str_replace('{site_mark}', strtolower($site_mark), $code);
            file_put_contents($save_path . 'EmptyController.php', $code);
        }
    }
    return true;
}

/**
 * [check_auth 用户授权]
 * @param  [type] $str    [用户功能]
 * @return [type]         [true/false]
 */
function check_auth($str)
{
    // 获取
    if (superman()) {
        return true;
    }

    // 用户授权
    $manage = cookie('admin_manage');
    $manageid = $manage['manage_id'];
    $group_id = $manage['manage_groupid'];

    $cache_name = 'cache_manage_group_' . $group_id;
    if (!cache('?' . $cache_name)) {
        $action = db('manage_group')->where('group_id', $group_id)->value('group_action');
        $action = explode(',', $action);
        cache($cache_name, $action);
    }
    return in_array($str, cache($cache_name));
}

/**
 * [superman 超级管理员]
 * @return [type] [description]
 */
function superman()
{
    // 获取 cookie
    $manage = cookie('admin_manage');
    $super = explode(',', config('superid'));
    if (in_array($manage['manage_id'], $super)) {
        return true;
    }

    return false;
}

/**
 * [encrypt_decrypt 加密解密]
 * @param  [type]  $key     [关键词]
 * @param  [type]  $string  [解密、加密]
 * @param  integer $decrypt [1 解密，0 加密]
 * @return [type]           [description]
 */
function encrypt_decrypt($key, $string, $decrypt = 0)
{
    if ($decrypt) {
        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
        return $decrypted;
    } else {
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
        return $encrypted;
    }
}

/**
 * 验证手机号是否正确
 * @author honfei
 * @param number $mobile
 */
function is_mobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^1[3,4,5,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
}

/**
 * 正则表达式验证email格式
 *
 * @param string $str    所要验证的邮箱地址
 * @return boolean
 */
function is_email($str)
{
    if (!$str) {
        return false;
    }
    return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $str) ? true : false;
}

/**
 * 显示分类
 * @param  [type] $str_id [需要显示的分类id]
 * @param  [type] $arg_cate [全部分类列表]
 * @return [type]      [description]
 */
function show_cate($str_id, $arg_cate)
{
    if ($str_id == '') {
        return '';
    }
    if (!is_array($arg_cate)) {
        return '';
    }
    $str_id = trim($str_id, '0,');
    $arg_id = explode(',', $str_id);
    $html = '';
    if (count($arg_id) > 1) {
        $menu = '';
        $num = 0;
        $dpname = '';
        foreach ($arg_id as $id) {
            if (!isset($arg_cate[$id])) {continue;}

            $num++;
            $name = $arg_cate[$id]['wscate_name'];
            if ($num == 1) {$dpname = $name;}

            $menu .= '<li><a>' . $name . '</a></li>';
        }
        $html = '<div class="dropdown dropdown-hover"><button type="button" class="btn btn-link" data-toggle="dropdown">%s <span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-table">%s</ul></div>';
        $html = sprintf($html, $dpname, $menu);

    } else {
        foreach ($arg_id as $id) {
            if (!isset($arg_cate[$id])) {continue;}
            $name = $arg_cate[$id]['wscate_name'];
            $html .= '<a class="btn btn-link">' . $name . '</a>';
        }
    }

    return $html;
}

/**
 * 显示分类
 * @param  [type] $str_id [需要显示的分类id]
 * @param  [type] $arg_cate [全部分类列表]
 * @return [type]      [description]
 */
function show_cate2($str_id, $arg_cate)
{
    if ($str_id == '') {
        return '';
    }
    if (!is_array($arg_cate)) {
        return '';
    }
    $str_id = trim($str_id, '0,');
    $arg_id = explode(',', $str_id);
    $html = '';
    $num = 0;
    foreach ($arg_id as $id) {
        if (!isset($arg_cate[$id])) {continue;}

        $num++;
        $name = $arg_cate[$id]['wscate_name'];
        if ($num == 1) {
            $html = $name;
        } else {
            $html .= ',' . $name;
        }
    }

    return $html;
}
